var app = angular.module("editApp", []),
	articleId = UI.getParameterByName('articleId'),
	ifmId = UI.getParameterByName('ifmId'),
	id = UI.getParameterByName('id'),
	parid = UI.getParameterByName('parId');

var timeout_json=function(data,$window){ 
	if (data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if (ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try{
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				}catch(e){ 
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

app.config(function($httpProvider,$compileProvider) {
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data) {
        /**
         * The workhorse; converts an object to x-www-form-urlencoded serialization.
         * @param {Object} obj
         * @return {String}
         */
        var param = function(obj) {
            var query = '';
            var name, value, fullSubName, subName, subValue, innerObj, i;
 
            for (name in obj) {
                value = obj[name];
 
                if (value instanceof Array) {
                    for (i = 0; i < value.length; ++i) {
                        subValue = value[i];
                        fullSubName = name + '[' + i + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value instanceof Object) {
                    for (subName in value) {
                        subValue = value[subName];
                        fullSubName = name + '[' + subName + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value !== undefined && value !== null) {
                    query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                }
            }
            return query.length ? query.substr(0, query.length - 1) : query;
        };
        return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
    }];
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|javascript):/);
});

app.controller('editCtrl', function($scope, $http,$window,$timeout) {
	var vm = $scope.vm = {
		articleId: articleId,
		title:'',
		articleType:'',
		url:'',
		content:'',
		websiteName:'',
		author:''
	};
	angular.element(window).bind('load', function() {
		//列表页面点击操作--修改--修改接口
		$http.get(basePath + 'Distribute/find.do?articleId='+articleId+'&ifmId='+ifmId).success(function(data) {
			//console.log(data)
			var j=timeout_json(data,$window);
			if(j==false){ 
				return false;
			}
			var editor="";
	    	window.htmlContent=data.returnData.content;
	    	$scope.vmm = data.returnData;
	    	$("#myEditor").val(window.htmlContent);
	    	window.editor= KindEditor.create("#myEditor", {
		            cssPath : basePath +'js/kindeditor-4.1.10/plugins/code/prettify.css',
//		            uploadJson : '<%=basePath%>uloadondown.action',//上传的请求
//		            fileManagerJson : '<%=basePath%>fmanage.action',
		            allowFileManager : true,
		            height:"300px",
		            resizeType:1  /*说明resizeType 2或1或0，2时可以拖动改变宽度和高度，1时只能改变高度，0时不能拖动。  数据类型: Int  默认值: 2 */
		        });			
			if($scope.vmm.articleType=="News"){
				$("#articleTypeId").val("新闻");
				$scope.authorOrWeixin = true;
			}else if($scope.vmm.articleType=="WeiXin"){
				$("#articleTypeId").val("微信");
				$scope.authorOrWeixin = false;
			}else if($scope.vmm.articleType=="Micro"){
				$("#articleTypeId").val("微博");
				$scope.authorOrWeixin = true;
			}else if($scope.vmm.articleType=="BBS"){
				$("#articleTypeId").val("论坛");
				$scope.authorOrWeixin = true;
			}
		});
	});
	
	$scope.toSource = function(){
		if($scope.vmm.url!=""){
			$scope.toSourceUrl = $scope.vmm.url;
		}else{
			$scope.toSourceUrl = 'javascript:void(0);';
		}
	}
	
	var avoidDup = true;
	$scope.domAjax = function(e) {
//		var data = $scope.content;
		if (e === "release") {
			if(avoidDup==false){
				return false;
			}
			if($scope.vmm.title!=undefined){vm.title=$scope.vmm.title;}
			vm.articleType=$("#artcleTE").val();
			if($scope.vmm.url!=undefined){vm.url=$scope.vmm.url;}
			if($scope.vmm.articleType!=undefined){
				vm.articleType=$scope.vmm.articleType;
			}
			if($scope.vmm.author!=undefined){vm.author=$scope.vmm.author;}
			if($scope.vmm.websiteName!=undefined){vm.websiteName=$scope.vmm.websiteName;}
			//html()包括标签的textarea内容，text()为textarea的纯文本内容
			vm.content=editor.text();
			//editor已定义为全局变量window。editor，同步数据可以直接取得textarea的value
			editor.sync();
			
//			vm.digest=$scope.vmm.myDigest;
//			if(vm.digest!=undefined){
//				vm.digest = vm.digest.replace(/<\/?.+?>/g,"").replace(/&nbsp;/g,"");
//				if(vm.digest.length>200){layer.msg('摘要不能超过200字！',1, -1);return false}
//			} 
			
			if(vm.title!=undefined){
				if(vm.title.length<=0){layer.msg('标题不能为空！',1, -1);return false}
				else if(vm.title.length>50){layer.msg('标题限于50字符以内！',1, -1);return false}
			}
			if(vm.author!=undefined){
				if(vm.author.length>50){layer.msg('作者限于50字符以内！',1, -1);return false}
			}
			if(vm.websiteName!=undefined){
				if(vm.websiteName.length<=0){layer.msg('首发媒体不能为空！',1, -1);return false}
				else if(vm.websiteName.length>50){layer.msg('首发媒体限于50字符以内！',1, -1);return false}
			}
//			vm.url = $scope.vmm.url;
			if(vm.url!=undefined){
				if(vm.url.length<=0){layer.msg('原文链接不能为空！',1, -1);return false}
				else if(vm.url.length>1000){layer.msg('原文链接限于1000字符以内！',1, -1);return false}
			}
			if(vm.content!=undefined){
				if(vm.content.length<=0){layer.msg('正文内容不能为空！',1, -1);return false}
			}	
//			//验证url地址
//			var strReg = "((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?";
//			var re = new RegExp(strReg);
//			if(!re.test($.trim(vm.url))) {
//				layer.msg("请输入有效的网址",2,-1);
//				return false;
//			}
			avoidDup =false;
			$http.post(basePath + 'Distribute/Update', vm).success(function(data) {
				var j=timeout_json(data,$window);
				if(j==false){ 
					return false;
				}
				if(data.returnCode==10000){
					layer.msg(data.returnMessage, 1, 10);
					//保存iframe窗口后，不跳转页面
					var t = setTimeout(function(){
						window.parent.$(".dtab").find('#jsgo a.cur').trigger('click');
						window.parent.layer.closeAll();
					},1000);
				}
				else{ 
					layer.msg(data.returnMessage, 2, -1);
					avoidDup =true;
					return false;
				}
			});
		}
	};
});

$(function() {
	laydate.skin('molv');
	$('.ui_select').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t'),
			_c = _.find('.ui_s_bk'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
			$("#artcleTE").val($(this).attr("type"));
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});

	$('.ui_select').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk'),
			di = 27;
		_.focus();
		e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
			sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t').blur();
		}
		return false;
	});
	
//	$("#myDigest").css({"min-height":"60px","width":"1040px","height":"auto","margin":"4px 8px","vertical-align":"middle","line-height":"18px"});
	$("#myEditor").css({"width":"100%","height":"auto"}); 
});
